package com.catfive.jet_work.feature.codeeditor

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.catfive.jet_work.core.design.component.TopBarIconMenuButton
import io.github.rosemoe.sora.langs.textmate.TextMateLanguage
import io.github.rosemoe.sora.widget.CodeEditor

@Composable
fun CodeEditorRoute(onOpenDrawer: () -> Unit) {
    CodeEditorScreen(onOpenDrawer = onOpenDrawer)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CodeEditorScreen(onOpenDrawer: () -> Unit) {
    val context = LocalContext.current
    var editor: CodeEditor? by remember { mutableStateOf(null) }

    Scaffold(topBar = {
        CenterAlignedTopAppBar(
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(0.6f)
            ),
            navigationIcon = {
                TopBarIconMenuButton(onClick = { onOpenDrawer() })
            },
            title = {
                Text("代码编辑", fontSize = 24.sp)
            }
        )
    }
    ) { paddingValue ->
        Surface(modifier = Modifier.padding(paddingValue)) {

            val context = LocalContext.current
            AndroidView(
                factory = { ctx ->
                    CodeEditor(ctx).apply {
                        editor = this // 保存 editor 实例供后续操作
                        setText("fun main() {\n    println(\"Hello, Sora!\")\n}")
//                        setEditorLanguage(TextMateLanguage.create("kotlin", themeStream = null)) // 基础高亮
                    }
                },
                modifier = Modifier.fillMaxSize(),

            )


        }
    }
}